# encoding: utf-8
# @File   : login_frame.py
# @Author : 乖孩子
# @Date   : 2025/07/24 16:30:30

import tkinter as tk
from tkinter import ttk, messagebox, scrolledtext
import threading
import os
from ui.theme import Theme
from core.auth import AuthCore


class LoginFrame(ttk.Frame):
    def __init__(self, parent, return_callback, logger, log_collector):
        super().__init__(parent, style="TFrame")
        self.parent = parent
        self.return_callback = return_callback
        self.logger = logger
        self.log_collector = log_collector
        self.auth_core = AuthCore(logger)

        # 创建UI
        self.create_widgets()

        # 加载最近登录信息
        self.load_recent_login()

        self.logger.info("登录界面初始化完成")

    def create_widgets(self):
        """创建登录界面组件"""
        # 标题
        ttk.Label(
            self,
            text="系统登录认证",
            font=Theme.FONTS["subtitle"],
            foreground=Theme.COLORS["primary"]
        ).pack(pady=20)

        # 登录卡片
        card = ttk.Frame(self, style="Card.TFrame")
        card.pack(fill=tk.X, padx=150, pady=10)

        # 表单区域
        form_frame = ttk.Frame(card, style="TFrame")
        form_frame.pack(fill=tk.X, pady=10)

        # 服务器IP
        ttk.Label(form_frame, text="服务器IP:").grid(row=0, column=0, sticky=tk.W, padx=30, pady=10)
        self.server_ip = tk.StringVar(value="192.168.1.111")
        server_entry = ttk.Entry(form_frame, textvariable=self.server_ip, width=30)
        server_entry.grid(row=0, column=1, sticky=tk.W, pady=10)

        # 用户名
        ttk.Label(form_frame, text="用户名:").grid(row=1, column=0, sticky=tk.W, padx=30, pady=10)
        self.username = tk.StringVar(value="YWRtaW4=")
        username_entry = ttk.Entry(form_frame, textvariable=self.username, width=30)
        username_entry.grid(row=1, column=1, sticky=tk.W, pady=10)

        # 密码
        ttk.Label(form_frame, text="密码:").grid(row=2, column=0, sticky=tk.W, padx=30, pady=10)
        self.password = tk.StringVar(value="5YtlqKUUEMU=")
        password_entry = ttk.Entry(form_frame, textvariable=self.password, show="*", width=30)
        password_entry.grid(row=2, column=1, sticky=tk.W, pady=10)

        # 添加输入框聚焦效果
        for entry in [server_entry, username_entry, password_entry]:
            entry.bind("<FocusIn>",
                       lambda e: e.widget.configure(highlightbackground=Theme.COLORS["accent"], highlightthickness=2))
            entry.bind("<FocusOut>", lambda e: e.widget.configure(highlightbackground="", highlightthickness=0))

        # 按钮区域
        btn_frame = ttk.Frame(card, style="TFrame")
        btn_frame.pack(fill=tk.X, pady=15)

        ttk.Button(
            btn_frame,
            text="登录",
            command=self.start_login,
            style="Accent.TButton"
        ).pack(side=tk.LEFT, padx=(50, 10))

        ttk.Button(
            btn_frame,
            text="清除",
            command=self.clear_fields
        ).pack(side=tk.LEFT, padx=10)

        ttk.Button(
            btn_frame,
            text="返回",
            command=self.return_callback
        ).pack(side=tk.RIGHT, padx=50)

        # 结果显示区域
        result_frame = ttk.LabelFrame(card, text="登录结果", style="TFrame")
        result_frame.pack(fill=tk.BOTH, expand=True, pady=10)

        # 状态行
        status_frame = ttk.Frame(result_frame, style="TFrame")
        status_frame.pack(fill=tk.X, pady=5)

        ttk.Label(status_frame, text="响应状态码:").pack(side=tk.LEFT, padx=5)
        self.status_code_label = ttk.Label(status_frame, text="等待登录...", foreground="blue")
        self.status_code_label.pack(side=tk.LEFT, padx=5)

        ttk.Label(status_frame, text="userID:").pack(side=tk.LEFT, padx=(30, 5))
        self.user_id_label = ttk.Label(status_frame, text="未获取")
        self.user_id_label.pack(side=tk.LEFT, padx=5)

        # 日志区域
        log_frame = ttk.Frame(result_frame, style="TFrame")
        log_frame.pack(fill=tk.BOTH, expand=True, pady=5)

        self.log_text = scrolledtext.ScrolledText(
            log_frame,
            height=8,
            font=Theme.FONTS["mono"],
            wrap=tk.WORD,
            relief=tk.FLAT,
            bd=1
        )
        self.log_text.pack(fill=tk.BOTH, expand=True, padx=5)
        self.log_text.insert(tk.END, "等待登录操作...\n")
        self.log_text.config(state=tk.DISABLED)

        # 设置错误标签样式
        self.log_text.tag_config("error", foreground=Theme.COLORS["danger"])

    def log_message(self, message, is_error=False):
        """日志输出到界面和收集器"""
        self.log_text.config(state=tk.NORMAL)

        if is_error:
            self.log_text.insert(tk.END, message + "\n", "error")
            self.logger.error(message)
            self.log_collector.add_log(message, "ERROR")
        else:
            self.log_text.insert(tk.END, message + "\n")
            self.logger.info(message)
            self.log_collector.add_log(message)

        self.log_text.see(tk.END)
        self.log_text.config(state=tk.DISABLED)

    def clear_fields(self):
        """清空输入字段"""
        self.log_message("清空登录表单")
        self.server_ip.set("")
        self.username.set("")
        self.password.set("")
        self.status_code_label.config(text="等待登录...", foreground="blue")
        self.user_id_label.config(text="未获取")

    def start_login(self):
        """开始登录"""
        server_ip = self.server_ip.get().strip()
        username = self.username.get().strip()
        password = self.password.get().strip()

        if not all([server_ip, username, password]):
            self.log_message("请填写完整登录信息", is_error=True)
            messagebox.showerror("错误", "请填写完整登录信息")
            return

        # 更新UI状态
        self.log_message("=" * 60)
        self.log_message(f"开始登录请求 - 服务器: {server_ip}")
        self.log_message(f"用户名: {username}")
        self.status_code_label.config(text="登录中...", foreground="orange")

        # 启动登录线程
        threading.Thread(
            target=self.auth_core.perform_login,
            args=(server_ip, username, password, self.handle_login_result),
            daemon=True
        ).start()

    def handle_login_result(self, success, data):
        """处理登录结果"""
        if success:
            self.status_code_label.config(text=str(data["status_code"]), foreground=Theme.COLORS["success"])
            self.user_id_label.config(text=str(data["user_id"]))
            self.log_message(f"☆ 登录成功! 状态码: {data['status_code']}")
            self.log_message(f"☆ 用户ID: {data['user_id']}")
            self.log_message(f"☆ 认证信息已保存到: {data['file_path']}")
        else:
            self.status_code_label.config(text="错误", foreground=Theme.COLORS["danger"])
            self.log_message(f"☆ 登录失败: {data['error']}", is_error=True)

        self.log_message("=" * 60)

    def load_recent_login(self):
        """加载最近登录信息"""
        # 实际应用中可以从配置文件加载
        self.log_message("加载最近登录信息")